# -*- coding: utf-8 -*-
from flask import jsonify, request, render_template, flash
from flask_login import current_user

from app.froms.book import SearchForm
from app.libs.helper import is_isbn_or_key
from app.models.gift import Gift
from app.models.wish import Wish
from app.spider.yushu_book import YuShuBook
from app.view_models.book import BookCollection, BookViewModel
from app.web import web


# http://localhost:8080/book/search?q=9787501524044&page=1
from app.web.trade import TradeInfo


@web.route('/book/search', methods=['Get', 'POST'])
def search():
    """
        书籍检索
        不缓存，缓存的意义很小，反而会占用内存
    """
    form = SearchForm(request.args)
    books = BookCollection()
    if form.validate():
        q = form.q.data.strip()
        page = form.page.data
        isbn_or_key = is_isbn_or_key(q)
        if isbn_or_key == 'isbn':
            yushu_book = YuShuBook()
            yushu_book.search_by_isbn(q)
        else:
            yushu_book = YuShuBook()
            yushu_book.search_by_keyword(q, page)
        books.fill(yushu_book, q)
    else:
        flash('搜索的关键字不符合要求，请重新输入关键字')
    return render_template('search_result.html', books=books)


@web.route('/book/test')
def test():
    result = {'name':"Jack",'age':'18'}
    flash('Hello,WJ', category='warning')
    return render_template('test.html', data=result)

@web.route('/book/<isbn>/detail')
# @cache.cached(timeout=1800)
def book_detail(isbn):
    has_in_gifts = False
    has_in_wishes = False

    yushu_book = YuShuBook()
    yushu_book.search_by_isbn(isbn)
    book = BookViewModel(yushu_book.first)

    if current_user.is_authenticated:
        if Gift.query.filter_by(uid=current_user.id, isbn=isbn, launched=False).first():
            has_in_gifts = True

        if Wish.query.filter_by(uid=current_user.id, isbn=isbn, launched=False).first():
            has_in_wishes = True


    trade_gifts = Gift.query.filter_by(isbn=isbn, launched = False).all()
    trade_wishes = Wish.query.filter_by(isbn=isbn, launched = False).all()

    trade_wishes_model = TradeInfo(trade_wishes)
    trade_gifts_model = TradeInfo(trade_gifts)


    return render_template('book_detail.html', book = book, wishes=trade_wishes_model,gifts = trade_gifts_model, has_in_gifts = has_in_gifts, has_in_wishes=has_in_wishes)

